/*
*Copyright 2021-2023 NERCIS
*
*Licensed under the Apache License, Version 2.0 (the "License");
*you may not use this file except in compliance with the License.
*You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
*Unless required by applicable law or agreed to in writing, software
*distributed under the License is distributed on an "AS IS" BASIS,
*WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*See the License for the specific language governing permissions and
*limitations under the License.
*/

package cn.ac.nercis.pes.community.controller.evaluation.prepare.asset;

import cn.ac.nercis.pes.common.constant.common.AssetConstants;
import cn.ac.nercis.pes.common.constant.evaluation.AssetSubBusinessReq;
import cn.ac.nercis.pes.community.component.dialog.*;
import cn.ac.nercis.pes.community.component.spreadsheet.asset.AssetSubBusinessSheetView;
import cn.ac.nercis.pes.community.manager.RealTimeSaveManager;
import cn.ac.nercis.pes.community.mapper.evaluation.AssetViewMapper;
import cn.ac.nercis.pes.community.model.vo.asset.KeyBusinessVO;
import cn.ac.nercis.pes.community.utils.*;
import cn.ac.nercis.pes.service.evaluation.AssetService;
import cn.ac.nercis.pes.service.project.SystemProcessService;
import javafx.application.Platform;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.control.Button;
import javafx.scene.control.Label;
import javafx.scene.layout.StackPane;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;

import java.net.URL;
import java.util.*;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutorService;

/**
 * 子对象(关键业务应用)--系统资产管理控制器
 *
 * @author zpy
 * @version 1.0.0
 */
@Slf4j
public class SubBusinessController extends BaseAssetController implements Initializable {
    @FXML
    private StackPane page;
    @FXML
    private Label titleLbl;
    @FXML
    private Button saveButton;

    @FXML
    private AssetSubBusinessSheetView sheetView;

    private final AssetService assetService;
    private final SystemProcessService processService;
    private final ExecutorService executor;

    private KeyBusinessVO currentKeyBusiness;
    private String currentSystemId;
    private final RealTimeSaveManager realTimeSaveManager = new RealTimeSaveManager(this::realTimeSave);

    public SubBusinessController() {
        this.assetService = SpringUtils.getBean(AssetService.class);
        this.processService = SpringUtils.getBean(SystemProcessService.class);
        this.executor = SpringUtils.getBean(ExecutorService.class);
    }

    @Override
    public void initialize(URL url, ResourceBundle resourceBundle) {
        saveButton.setGraphic(IconUtils.getGlyph("save-button-icon","tool-button-icon"));
        saveButton.disableProperty().bind(this.dataSaving);
        GuiStore.applyQuickSave(this.page, this::onGlobalSave);
        realTimeSaveManager.listenerSheetChange(this.sheetView);
    }

    public void initializeData(String systemId,KeyBusinessVO keyBusiness){
        LogUtils.info(log, "初始化系统资产-子对象信息...");
        this.currentSystemId = systemId;
        this.currentKeyBusiness = keyBusiness;
        this.titleLbl.setText(keyBusiness.getName());
        this.sheetView.initialize(keyBusiness,this::onDeleteAsset);
        this.queryAsset();
    }

    @Override
    public void onGlobalSave() {
        LogUtils.info(log, "执行快捷保存操作...");
        batchSave(false);
    }

    @FXML
    public void onSave(){
        LogUtils.info(log, "执行保存操作...");
        this.batchSave(false);
    }

    public void realTimeSave(){
        LogUtils.info(log, "执行即时保存操作...");
        this.batchSave(true);
    }

    public void onDeleteAsset(Set<String> ids){
        LogUtils.info(log, "执行删除操作...");
        if(CollectionUtils.isEmpty(ids)){
            return;
        }
        AlertDialog alertDialog = AlertDialog.builder()
                .withMode(AlertMode.CONFIRM)
                .withType(AlertType.WARN)
                .withTitle("删除提示")
                .withContent("确认删除当前子对象信息吗？")
                .withContainer(this.page)
                .build();
        alertDialog.show((confirm)->{
            if(!confirm){
                return;
            }
            checkDeleteAsset(ids);
        });
    }

    @Override
    protected StackPane getPage() {
        return this.page;
    }

    @Override
    protected String getCurrentSystemId() {
        return this.currentSystemId;
    }

    @Override
    protected AssetService getAssetService() {
        return this.assetService;
    }

    @Override
    protected SystemProcessService getProcessService() {
        return this.processService;
    }

    @Override
    protected ExecutorService getExecutorService() {
        return this.executor;
    }

    @Override
    public void initializeData(String systemId) {
    }

    @Override
    protected void onSuccessImport() {
    }

    @Override
    protected void refreshFinishProcess(boolean finish) {
    }

    @Override
    protected void queryAsset() {
        this.refreshReqList();
        LogUtils.info(log, "获取系统资产-子对象信息...");
        LogUtils.record(log, "请求数据，systemId:{}，filter:{}", this.currentSystemId, this.currentKeyBusiness.getId());
        CompletableFuture.supplyAsync(() -> this.assetService.findSubBusiness(this.currentSystemId,this.currentKeyBusiness.getId()),this.executor)
                .thenAccept(res -> Platform.runLater(() -> {
                    var data = res.stream()
                            .map(AssetViewMapper.INSTANCE::toVO)
                            .toList();
                    this.sheetView.loadContent(data);
                }))
                .exceptionally((ex) -> {
                    log.error("获取系统资产-子对象信息出错!", ex);
                    MessageDialog.builder()
                            .withContainer(this.page)
                            .withType(MessageType.FAIL).withMessage("加载数据表内容失败！")
                            .build().show();
                    return null;
                });
    }

    private void refreshReqList(){
        var systemInfo = AppStore.getCurrentSystem(this.currentSystemId);
        this.sheetView.refreshReqData(AssetSubBusinessReq.getReqNames(systemInfo.getSecurityLevel()));
    }

    private void batchSave(boolean realTime) {
        if (!this.sheetView.validate()) {
            if (!realTime) {
                AppUtils.showMessageDialog("以下标出的子对象的必填信息不能为空", MessageType.WARN, this.page);
            }
            return;
        }
        var systemInfo = AppStore.getCurrentSystem(this.currentSystemId);
        List<String> reqNames = AssetSubBusinessReq.getReqNames(systemInfo.getSecurityLevel());
        var assetData = this.sheetView.getModifyData().stream()
                .filter(data -> {
                    List<String> list = new ArrayList<>();
                    if (StringUtils.isNotBlank(data.getRequire())) {
                        list = Arrays.stream(data.getRequire().split(AssetConstants.KEY_DATA_REQ_SPLIT)).toList();
                    }
                    if (StringUtils.isBlank(data.getRequire()) || reqNames.containsAll(list)) {
                        return true;
                    } else {
                        return false;
                    }
                })
                .map(AssetViewMapper.INSTANCE::toDTO)
                .toList();
        if (!realTime && CollectionUtils.isEmpty(assetData)) {
            AppUtils.showMessageDialog("保存成功", MessageType.SUCCESS, this.page);
            return;
        }
        this.dataSaving.setValue(true);
        LogUtils.info(log, "批量保存系统资产-子对象信息...");
        LogUtils.record(log, "请求数据，systemId：{},data:{}", this.currentSystemId, assetData);
        //未保存的数据进行批量保存
        CompletableFuture.supplyAsync(() -> this.assetService.batchSaveSubBusiness(this.currentSystemId,this.currentKeyBusiness.getId(), assetData),this.executor)
                .thenAccept(res -> Platform.runLater(() -> {
                    this.dataSaving.setValue(false);
                    if (res.isSuccess()) {
                        //更新表数据
                        this.queryAsset();
                        if(!realTime){
                            AppUtils.showMessageDialog("保存成功",MessageType.SUCCESS,this.page);
                        }
                    } else {
                        if(realTime){
                            log.error("即时保存系统资产-子对象信息失败：{}",res.getMsg());
                        }else{
                            AppUtils.showMessageDialog(res.getMsg(),MessageType.FAIL,this.page);
                        }
                    }
                }))
                .exceptionally((ex) -> {
                    this.dataSaving.setValue(false);
                    log.error("批量保存系统资产-子对象信息出错!", ex);
                    return null;
                });
    }

}